package com.xunfang.controller;

import com.xunfang.utils.QiNiuUploadUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
@Tag(name = "文件上传")
public class UploadController{

    // @RequestPart 接受 前端 传递过来的图片
    @Operation(summary = "文件上传")
    @PostMapping("/images")
    public ResponseEntity<String> upload(@RequestPart MultipartFile file) throws IOException {
        System.out.println("upload");
        // 1. 获取文件名称
        String originalFilename = file.getOriginalFilename();
        //c:/xxx/a.png  ===> xxx.png
        //  截取图片后缀  png
        //  xxx  通过uuid 唯一码 进行生成
        // 2. 重新设置文件的名称
        String uuid = UUID.randomUUID().toString();
        // 文件的名称 = uuid + 源文件的后缀
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = uuid + substring;
        fileName.replaceAll("-", "");
        // 3. 调用图片上传的工具类
        String pathUrl = QiNiuUploadUtils.uploadFile(file.getBytes(), fileName);

        // 4. 响应数据
        return ResponseEntity.ok(pathUrl);
    }

    @Operation(summary = "删除图片")
    @GetMapping("/delete")
    public ResponseEntity delete(String fileName){
        QiNiuUploadUtils.deleteFile(fileName);
        return ResponseEntity.ok().build();
    }
}